<template>
  <el-dialog
    v-bind="$attrs"
    width="600px"
    :title="$t('flyparam.rename_table')"
    v-on="$listeners"
    @open="open"
    @close="close"
  >
    <el-form ref="form" :model="form" @submit.native.prevent="confirm">
      <el-form-item
        required
        prop="tableName"
        :label="$t('flyparam.table_name')"
        :rules="[{ validator: validateTableName }]"
      >
        <el-input
          v-model="form.tableName"
          :maxlength="64"
          @blur="form.tableName = form.tableName.trim()"
        />
      </el-form-item> </el-form
    ><template #footer>
      <div>
        <el-button size="small" @click="close">{{
          $t('common.cancel')
        }}</el-button>
        <el-button
          :loading="loading"
          size="small"
          type="primary"
          native-type="submit"
          @click="confirm"
          :disabled="form.tableName === tableName"
          >{{ $t('common.confirm') }}</el-button
        >
      </div></template
    >
  </el-dialog>
</template>

<script>
import { updateTable } from '@/api/parameter'
import { i18n } from '@/lang'
export default {
  inheritAttrs: false,
  props: {
    tableId: String,
    tableName: String,
    tabs: Array
  },
  data() {
    return {
      loading: false,
      form: {
        tableName: ''
      },
      validateTableName: (rule, value, callback) => {
        if (/^\s+$/.test(value)) {
          // 纯空格报错
          return callback(new Error(i18n.t('flyparam.invalid_input')))
        }
        callback()
      }
    }
  },
  methods: {
    close() {
      this.$emit('update:model-value', false)
      this.$refs.form.resetFields()
    },
    open() {
      this.$nextTick(() => {
        this.form.tableName = this.tableName
      })
    },
    confirm() {
      return new Promise((resolve, reject) => {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.loading = true
            updateTable(this.$route.params.id, this.tableId, this.form)
              .then(() => {
                this.loading = false
                const tab = this.tabs.find((tab) => tab.id === this.tableId)
                tab.name = this.form.tableName
                this.$emit('save')
                this.$message.success(
                  this.$t('common.message.operation_success')
                )
                this.$emit('update:model-value', false)

                resolve()
              })
              .catch((err) => {
                this.loading = false
                this.$message.error(err)
                reject(err)
              })
          }
        })
      })
    }
  }
}
</script>

<style>
</style>
